#ifndef _X_UTIL_H
#define _X_UTIL_H
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <signal.h>
namespace XUtil
{
    static bool CreatePidFile()
    {
        int fd = open("./.pid", O_TRUNC | O_RDWR);
        if (fd == -1)
        {
            fd = open("./.pid", O_CREAT | O_RDWR, 0644);
            if (fd == -1)
            {
                return false;
            }
        }
        pid_t pid = getpid();
        char sz_pid[64];
        memset(sz_pid, 0, sizeof(sz_pid));
        sprintf(sz_pid, "%d", pid);

        ssize_t dwRlt = write(fd, sz_pid, strlen(sz_pid));
        close(fd);
        return true;
    }
    static int DaemonInit()
    {
        int		i;
        pid_t	pid;

        if( ( pid = fork() ) < 0 )
            return ( -1 );
        else if( pid )
        {
            //assert( 0 );
            _exit( 0 );/* parent terminates */
        }

        /* child 1 continues... */
        if( setsid() < 0 )/* become session leader */
            return ( -1 );

        signal( SIGHUP, SIG_IGN );
        if( ( pid = fork() ) < 0 )
            return ( -1 );
        else if( pid )
        {
            //assert( 0 );
            _exit( 0 );/* child 1 terminates */
        }

        /* child 2 continues... */
        //daemon_proc = 1;/* for err_XXX() functions */
        /* close off file descriptors */
        struct rlimit limitQ;
        if(getrlimit(RLIMIT_NOFILE,&limitQ) != -1)
        {
            printf("getrlimit = %d\n",(int)limitQ.rlim_cur);

            /* close off file descriptors */
    //        for(int i = 0 ; i < (int)limitQ.rlim_cur ; i ++ )
    //            close( i );
        }
    //    else
    //    {
            for(int i = 0 ; i < 64 ; i ++ )
                close( i );
    //    }
        /* redirect stdin, stdout, and stderr to /dev/null */
        open( "/dev/null", O_RDONLY );
        open( "/dev/null", O_RDWR );
        open( "/dev/null", O_RDWR );

        //openlog(pname, LOG_PID, facility);

        return ( 0 );/* success */
    }

};

#endif